package org.abettor.angleworm.media.rtp;

import java.io.IOException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.abettor.angleworm.media.MediaTransmitter;
import org.abettor.angleworm.media.MediaTransmitterFactory;
import org.abettor.angleworm.media.MediaTransmitterManager;

/**
 * <p>通过RTP/UDP协议传输媒体流的媒体传输类的工厂类</p>
 * <p>支持的目标URL格式为：<i>rtp://&lt;Dest IP address | Dest host name&gt;:&lt;Dest port&gt;</i></p>
 * @author shawn
 *
 */
public class RtpTransmitterFactory implements MediaTransmitterFactory
{
	private static final String REGEX_IP_ADDR = "((\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])";
	private static final String REGEX_HOST_NAME = "[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})*";
	private static final String REGEX_TARGET_URL = "^rtp://((" + REGEX_IP_ADDR + ")|(" + REGEX_HOST_NAME + ")):[0-9]{1,5}$";

	public static final String PROPERTY_BIND_LOCAL_ADDR = "rtpTransmitter.bind.localAddr";

	//	按照规范，向媒体传输程序管理类注册本工厂类
	static
	{
		MediaTransmitterManager.register(new RtpTransmitterFactory());
	}

	/**
	 * @see org.abettor.angleworm.media.MediaTransmitterFactory#support(String)
	 */
	@Override
	public boolean support(String targetUrl)
	{
		Pattern pattern = Pattern.compile(REGEX_TARGET_URL);
		Matcher matcher = pattern.matcher(targetUrl);
		if(matcher.find())
		{
			return true;
		}

		return false;
	}

	/**
	 * @see org.abettor.angleworm.media.MediaTransmitterFactory#createTransmitter(String, Properties)
	 */
	@Override
	public MediaTransmitter createTransmitter(String targetUrl, Properties properties) throws IOException
	{
		//	创建传输程序实例
		RtpTransmitter trans = new RtpTransmitter(targetUrl);

		//	设置附加参数
		if(properties != null)
		{
			String localAddr = properties.getProperty(PROPERTY_BIND_LOCAL_ADDR);
			if(localAddr != null && ! localAddr.isEmpty())
			{
				trans.setBindAddress(localAddr);
			}
		}

		return trans;
	}
}
